package com.yxdj.auth.controller;

import com.yxdj.auth.form.AppLoginDto;
import com.yxdj.auth.service.AppUserService;
import com.yxdj.common.core.domain.R;
import com.yxdj.common.core.utils.JwtUtils;
import com.yxdj.common.core.utils.StringUtils;
import com.yxdj.common.security.auth.AuthUtil;
import com.yxdj.common.security.service.TokenService;
import com.yxdj.common.security.utils.SecurityUtils;
import com.yxdj.system.api.model.LoginUser;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Tag(name = "App用户登录管理")
@RestController
@RequestMapping("/appUser")
public class AppUserController
{
    @Autowired
    private TokenService tokenService;

    @Autowired
    private AppUserService appUserService;

    @Operation(summary = "登录")
    @PostMapping("/login")
    public R<?> login(@RequestBody AppLoginDto form)
    {
        // 用户登录
        LoginUser loginUser = appUserService.login(form.getPhone(), form.getCode());
        // 获取登录token
        Map<String, Object> token = tokenService.createToken(loginUser);
        token.put("name", loginUser.getSysUser().getNickName());
        token.put("avatarUrl",loginUser.getSysUser().getAvatar());
        return R.ok(token);
    }

    @Operation(summary = "退出登录")
    @DeleteMapping("/logout")
    public R<?> logout(HttpServletRequest request)
    {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token))
        {
            String username = JwtUtils.getUserName(token);
            // 删除用户缓存记录
            AuthUtil.logoutByToken(token);
            // 记录用户退出日志
            appUserService.logout(username);
        }
        return R.ok();
    }
}
